package com.laoma.usercenter.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.laoma.usercenter.common.CommonException;
import com.laoma.usercenter.common.CommonResponse;
import com.laoma.usercenter.dto.response.UserInfoResponse;
import com.laoma.usercenter.handler.FallbackHandler;
import com.laoma.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @program: SpringCloudDemos
 * @description:
 * @author: 老马
 * @create: 2021-06-16 09:08
 **/
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Resource
    private UserService userService;
    @Value("${server.port}")
    private String port;

    @GetMapping("/port.json")
    public CommonResponse getLBport() {
        return CommonResponse.buildSuccessCommonResponseWithData(port);
    }

    @GetMapping("/error.json")
    public CommonResponse testError() {
        int i = 1/0;
        return CommonResponse.buildSuccessCommonResponse();
    }

    @GetMapping("/{wxid}/info.json")
    public UserInfoResponse getUserInfo(HttpServletRequest request,  @PathVariable String wxid) {
        log.info("请求到端口: {}", request.getRemotePort());
        return this.userService.getUserInfoByWxId(wxid);
    }


    @GetMapping("/userinfo.json")
    public UserInfoResponse getUserById(String wxid) {
        return this.userService.getUserInfoByWxId(wxid);
    }

    @GetMapping("/testFallback.json")
    @SentinelResource(value = "testFallback",
            fallback = "handleFallback",
            fallbackClass = FallbackHandler.class,
            blockHandler = "handleBlockHandler",
            blockHandlerClass = FallbackHandler.class
    )
    public CommonResponse testFallback(String wxid) {

        if("123456".equals(wxid)) {
            throw new RuntimeException("微信ID不存在");
        }
        return CommonResponse.buildSuccessCommonResponseWithData("hello -->" + wxid);
    }

    @GetMapping("/testGlobalFall.json")
    public CommonResponse testGlobalFall(String wxid) throws CommonException {

        if("123456".equals(wxid)) {
            throw CommonException.buildCommonException("微信ID不存在");
        }
        return CommonResponse.buildSuccessCommonResponseWithData("hello -->" + wxid);
    }


    //本类处理异常发生的返回
    public CommonResponse handleFallback(String wxid, Throwable e) {
        //这里可以自定义的处理各种的异常
        if(e instanceof RuntimeException) {
            log.error(e.getMessage());
        }
        return CommonResponse.buildFailCommonResponse(String.format(e.getMessage() + "【%s】", 123456));
    }


}
